package com.bpz.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.net.URL;

/*
 * 数据对象缓存基本类
 * */
public class EhCacheUtil {

	private static final String path = "/ehcache.xml";

	private URL url;

	private CacheManager manager;

	private EhCacheUtil(String path) {
		url = getClass().getResource(path);
		manager = CacheManager.create(url);
	}

	private static EhCacheUtil instance = null;

	/*
	 * 单例
	 */
	public static EhCacheUtil getInstance() {
		if (instance == null) {
			synchronized (EhCacheUtil.class) {
				if (instance == null) {
					instance = new EhCacheUtil(path);
				}
			}
		}
		return instance;
	}

	/*
	 * 存入cache
	 */
	public void put(String cacheName, String key, Object value) {
		Cache cache = manager.getCache(cacheName);
		Element element = new Element(key, value);
		cache.put(element);
	}

	/*
	 * 获得缓存中存的数据
	 */
	public Object get(String cacheName, String key) {
		Cache cache = manager.getCache(cacheName);
		Element element = cache.get(key);
		return element == null ? null : element.getObjectValue();
	}

	/*
	 * 获取指定cachename的cache对象
	 */
	public Cache get(String cacheName) {
		return manager.getCache(cacheName);
	}

	public void remove(String cacheName, String key) {
		Cache cache = manager.getCache(cacheName);
		cache.remove(key);
	}

}
